package com.example.multithread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Ticket {
    private int count = 3;
    private Lock lock = new ReentrantLock();

    public void sale() {
        this.lock.lock();
        try {
            if (this.count > 0) {
                TimeUnit.SECONDS.sleep(1);
                System.out.printf("【%s】卖票，剩余票数: %d%n", Thread.currentThread().getName(), this.count--);
            } else {
                System.out.printf("【%s】票已经卖完啦，明天请早! %n", Thread.currentThread().getName());

            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            this.lock.unlock();
        }
    }
}

/**
 * 卖票 ReentrantLock 互斥锁实现方式
 */
public class ReentrantLockTest {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                ticket.sale();
            }, "售票员-" + i).start();
        }
    }
}
